package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.domain.Employee;

import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


@RestController
@Slf4j
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession httpSession;


    //登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {

        //接受参数
        String username = map.get("username");
        String password = map.get("password");
        //调用方法，返回标识
        ResultInfo resultInfo = employeeService.login(username,password);
        //如果登录成功，将对象保存在session
        if (resultInfo.getCode() == 1) {
            Employee employee = (Employee) resultInfo.getData();
            httpSession.setAttribute(Constant.SESSION_EMPLOYEE, employee);
        }
        return resultInfo;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        //清楚数据
        httpSession.invalidate();
        //返回标识
        return ResultInfo.success(null);
    }

    //查询员工列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name) {
        //调用方法
        List<Employee> employeeList = employeeService.findByName(name);
        //查询结果
        return ResultInfo.success(employeeList);
    }

    //保存
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        //接收参数打印
//        log.info(employee.toString());
        //调用方法
        employeeService.save(employee);
        //返回结果
        return ResultInfo.success(null);
    }

    //根据id查询
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        //接受id参数打印
//        log.info(String.valueOf(id));
        //调用方法
        Employee employee = employeeService.findById(id);
        //返回结果
        return ResultInfo.success(employee);
    }

    //修改
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        //接受参数
//        log.info(employee.toString());
        //调用方法
        employeeService.update(employee);
        //返回结果
        return ResultInfo.success(null);
    }
}
